<template>
	<component :is="renderLoop(column)"></component>
</template>

<script lang="tsx" setup>
import { inject, ref, useSlots } from 'vue';
import { ElTableColumn, ElTag } from 'element-plus';
import { filterEnum, formatValue, handleRowAccordingToProp } from '@/utils/util';
import { ColumnProps } from '@/components/ProTable/interface';
import { useCheckout } from '@/hooks/useCheckout';
import { formatDate } from '@/utils/util';
const { hideCertno } = useCheckout();
const slots = useSlots();

defineProps<{ column: ColumnProps }>();

const enumMap = inject('enumMap', ref(new Map()));

// 渲染表格数据
const renderCellData = (item: ColumnProps, scope: { [key: string]: any }) => {
	return enumMap.value.get(item.prop) && item.isFilterEnum
		? filterEnum(handleRowAccordingToProp(scope.row, item.prop!), enumMap.value.get(item.prop)!, item.fieldNames)
		: formatValue(handleRowAccordingToProp(scope.row, item.prop!));
};
// 获取 tag 类型
const getTagType = (item: ColumnProps, scope: { [key: string]: any }) => {
	return filterEnum(handleRowAccordingToProp(scope.row, item.prop!), enumMap.value.get(item.prop), item.fieldNames, 'tag') as any;
};

// 设置最小宽度
const setMinPropWidth = (item: ColumnProps | any) => {
	if (item.minWidth) {
		return item.minWidth;
	}
	if (item.prop && ['Code', 'Id', 'phone', 'email', 'Name', 'Time', 'Date'].some(key => item.prop.includes(key))) {
		return 200;
	}
	if (item.prop && ['Dscr', 'remarks'].some(key => item.prop.includes(key))) {
		return 300;
	}

	return 100;
};

const renderLoop = (item: ColumnProps) => {
	return (
		<>
			{item.isShow && (
				<ElTableColumn
					{...item}
					width={item.width}
					min-width={setMinPropWidth(item)}
					align={item.align ?? 'center'}
					showOverflowTooltip={item.showOverflowTooltip ?? item.prop !== 'operation'}
				>
					{{
						default: (scope: any) => {
							if (item._children) return item._children.map(child => renderLoop(child));
							{
								/* 身份证加密 */
							}
							if (item.prop!.indexOf('Certno') !== -1 || item.prop!.indexOf('certno') !== -1) {
								return hideCertno(scope.row![item.prop!]);
							}
							// 日期格式化
							if (item.tableType) {
								return formatDate(scope.row![item.prop!], item.tableType);
							}
							{
								/* render函数 */
							}
							if (item.render) return item.render(scope);
							{
								/* 插槽 */
							}
							if (slots[item.prop!]) return slots[item.prop!]!(scope);
							if (item.tag) return <ElTag type={getTagType(item, scope)}>{renderCellData(item, scope)}</ElTag>;
							return renderCellData(item, scope);
						},
						header: () => {
							{
								/* 自定义表头render函数 */
							}
							if (item.headerRender) return item.headerRender(item);
							{
								/* 表头插槽 */
							}
							if (slots[`${item.prop}Header`]) return slots[`${item.prop}Header`]!({ row: item });
							return item.label;
						}
					}}
				</ElTableColumn>
			)}
		</>
	);
};
</script>
